package com.linghang.association.service;
import com.github.pagehelper.PageHelper;
import com.linghang.association.domain.*;
import com.linghang.association.exception.BusinessException;
import com.linghang.association.exception.BusinessExceptionCode;
import com.linghang.association.mapper.*;
import com.linghang.association.req.*;
import com.linghang.association.resp.UserAdminResp;
import com.linghang.association.resp.UserLoginResp;
import com.linghang.association.resp.ViewAdminResp;
import com.linghang.association.utils.CopyUtil;
import com.linghang.association.utils.MD5Util;
import com.linghang.association.utils.PaeseTokenUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
/**
 * @author LinyaT052
 * @date 2022年07月17日 16:20
 */

/**
 * @Service注解表示将此类交给Spring来进行管理
 */
@Service
public class UserService {
    private static final Logger LOG = LoggerFactory.getLogger(UserService.class);
    @Resource
    private JavaMailSender javaMailSender;
    @Resource
    private UserMapper userMapper;
    @Resource
    private ResourceMapper resourceMapper;
    @Resource
    private UserSignUpMapper userSignUpMapper;
    @Resource
    private UserRoleMapper userRoleMapper;
    @Resource
    private DepartmentMapper departmentMapper;
    @Resource
    private MinisterMapper ministerMapper;
    @Resource
    private DailyMapper dailyMapper;
    @Resource
    private DepartMsgMapper departMsgMapper;
    @Resource
    private DepartQQMapper departQQMapper;
    @Resource
    private DepartReqMapper departReqMapper;
    @Resource
    private DepartSloMapper departSloMapper;
    @Resource
    private InterestMapper interestMapper;
    @Resource
    private DepartWorkMapper departWorkMapper;
    @Resource
    private  RoleMapper roleMapper;
    @Resource
    private NoticeMapper noticeMapper;
    /**
     * 登录
     * @param req
     * @return
     */
    public UserLoginResp login(@RequestBody UserLoginReq req) {
            User userDb = selectByUsername(req.getUsername());
            if(userDb == null){
                //用户名不存在
                LOG.info("用户名不存在{}",req.getUsername());
                throw new BusinessException(BusinessExceptionCode.LOGIN_USER_ERROR);
            }else {
                //用户名存在继续判断密码
                if(userDb.getPassword().equals(new String(MD5Util.getMD5(req.getPassword())))){
                UserLoginResp resp = CopyUtil.copy(userDb, UserLoginResp.class);
                LOG.info("" + resp);
                LOG.info("用户:{}登录成功", req.getUsername());
                return resp;
                }else {
                    //密码错误
                    LOG.info("" + userDb);
                    LOG.info("密码不正确，输入密码{}，数据库密码{}", req.getPassword(), userDb.getPassword());
                    throw new BusinessException(BusinessExceptionCode.LOGIN_USER_ERROR);
                }
            }
    }

    /**
     * 根据用户名查找用户信息
     * @param username
     * @return
     */
    public  User selectByUsername(String username){
        UserExample UserExample = new UserExample();
        UserExample.Criteria criteria = UserExample.createCriteria();
        criteria.andUsernameEqualTo(username);
        List<User> userList = userMapper.selectByExample(UserExample);
        if(CollectionUtils.isEmpty(userList)){
            return null;
        }else{
            return userList.get(0);
        }
    }
    /**
     * 重置密码
     */
    public void resetPassword(UserResetPasswordReq req){
        //拷贝请求数据到用户实体对象
            User user = CopyUtil.copy(req,User.class);
            LOG.info(""+user);
            //将用户密码加密储存到数据库
            String MD5 = new String(MD5Util.getMD5(user.getPassword()));
            user.setPassword(MD5);
            userMapper.updateByPrimaryKeySelective(user);
    }
    /**
     * 用户报名接口
     * @param req
     */
    public void sign_in(UserSignUpReq req) {
        //拷贝请求数据到用户实体对象
        try{
        UserSignUp userSignUp = CopyUtil.copy(req,UserSignUp.class);
        userSignUp.setStatu(2);
        userSignUpMapper.insertSelective(userSignUp);
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 查看所有用户信息
     */
    public List<UserSignUp> ViewInfoAll(HttpServletRequest request,PageReq req) {
        //从请求头中取出token并解析
       String token = request.getHeader("token");
       //获取响应实体
       UserAdminResp resp = PaeseTokenUtil.getUser(token);
       List<com.linghang.association.domain.Resource> au = resourceMapper.selectByUsername(resp.getUsername());
       LOG.info(""+au);
       for(int i=0;i<au.size();i++){
           //判断是否拥有id为3的权限
           if(au.get(i).getId() == 3)
               PageHelper.startPage(req.getPage(),req.getSize());
               return userSignUpMapper.selectByExample(null);
       }
           //权限不足抛出异常
           throw new BusinessException(BusinessExceptionCode.LACK_AUTHORITY);
    }

    /**
     * 查看对应分管部门的报名信息
     * @param req
     * @return
     */
    public List<UserSignUp> ViewDepartInfo(HttpServletRequest request,PageReq req) {
        String token = request.getHeader("token");
        //获取响应实体
        UserAdminResp resp = PaeseTokenUtil.getUser(token);
        List<com.linghang.association.domain.Resource> au = resourceMapper.selectByUsername(resp.getUsername());
        LOG.info("" + au);
        for (int i = 0; i < au.size(); i++) {
            //判断是否拥有id为2的权限
            if (au.get(i).getId() == 2) {
                UserSignUpExample example = new UserSignUpExample();
                UserSignUpExample.Criteria criteria = example.createCriteria();
                criteria.andDepartmentIdEqualTo(userMapper.selectDepartmentId(resp.getUsername()));
                PageHelper.startPage(req.getPage(),req.getSize());
                return userSignUpMapper.selectByExample(example);
            }
        }
            //权限不足抛出异常
            throw new BusinessException(BusinessExceptionCode.LACK_AUTHORITY);
    }

    /**
     * 添加新管理员
     * @param username
     * @param roleId
     */
    public void EditAdminInfo(HttpServletRequest request,String username, Integer roleId) {
        String token = request.getHeader("token");
        //获取响应实体
        UserAdminResp resp = PaeseTokenUtil.getUser(token);
        List<com.linghang.association.domain.Resource> au = resourceMapper.selectByUsername(resp.getUsername());
        LOG.info("" + au);
        for (int i = 0; i < au.size(); i++) {
            //判断是否拥有id为4的权限
            if (au.get(i).getId() == 4) {
                UserRole userRole = new UserRole(username,roleId);
                userRoleMapper.insert(userRole);
                return;
            }
        }
        //权限不足抛出异常
        throw new BusinessException(BusinessExceptionCode.LACK_AUTHORITY);
    }
    /**
     * 管理员审核报名信息
     */
    public void VerifySignUp(HttpServletRequest request,Integer status) {
        String token = request.getHeader("token");
        //获取响应实体
        UserAdminResp resp = PaeseTokenUtil.getUser(token);
        UserSignUp signUp = new UserSignUp();
        signUp.setStatu(status);
        List<com.linghang.association.domain.Resource> au = resourceMapper.selectByUsername(resp.getUsername());
        LOG.info("" + au);
        for (int i = 0; i < au.size(); i++) {
            //判断是否拥有id为1的权限
            //拥有则将审核状态改变
            if (au.get(i).getId() == 1) {
                userSignUpMapper.insertSelective(signUp);
                //同时发送邮件到指定邮箱
                this.sendEmail(signUp.getStuQq());
                return;
            }
        }
        //权限不足抛出异常
        throw new BusinessException(BusinessExceptionCode.LACK_AUTHORITY);
    }

    /**
     *生成新管理员
     * @param request
     * @param req
     */
    public void newAdminister(HttpServletRequest request, NewAdminReq req) {
        String token = request.getHeader("token");
        //获取响应实体
        UserAdminResp resp = PaeseTokenUtil.getUser(token);
        List<com.linghang.association.domain.Resource> au = resourceMapper.selectByUsername(resp.getUsername());
        LOG.info("" + au);
        for (int i = 0; i < au.size(); i++) {
            //判断是否拥有id为4的权限
            if (au.get(i).getId() == 4) {
                //拥有则在用户表中插入新数据
                String password = new String(MD5Util.getMD5(req.getPassword()));//密码加密储存
                userMapper.insert(new User(req.getUsername(),password,req.getDepartment()));
                //同时在用户角色表插入数据
                userRoleMapper.insert(new UserRole(req.getUsername(),departmentMapper.selectAdminIdById(req.getDepartment())));
                return;
            }
        }
        //权限不足抛出异常
        throw new BusinessException(BusinessExceptionCode.LACK_AUTHORITY);
    }

    /**
     * 编辑社团信息
     * @param request
     * @param departInfo
     */
    public void EditDepartInfo(HttpServletRequest request, DepartInfo departInfo) {
        String token = request.getHeader("token");
        //获取响应实体
        UserAdminResp resp = PaeseTokenUtil.getUser(token);
        List<com.linghang.association.domain.Resource> au = resourceMapper.selectByUsername(resp.getUsername());
        LOG.info("" + au);
        for (int i = 0; i < au.size(); i++) {
            //判断是否拥有id为6的权限
            if (au.get(i).getId() == 6) {
                //拥有则在社团表中更新数据
                //向日常活动中插入数据
                dailyMapper.insert(new Daily(departInfo.getActivities(),departInfo.getPhotoShow(),resp.getDepartId()));
                //向标语中插入数据
                departSloMapper.insert(new DepartSlo(departInfo.getSlogan(),resp.getDepartId()));
                //向部门基本信息中插入数据
                departMsgMapper.insert(new DepartMsg(departInfo.getMessage(),resp.getDepartId()));
                //向主要工作中插入数据
                departWorkMapper.insert(new DepartWork(departInfo.getWorks(),resp.getDepartId()));
                //向加入部门好处中插入数据
                interestMapper.insert(new Interest(departInfo.getInterest(),resp.getDepartId()));
                //向加入部门要求中插入数据
                departReqMapper.insert(new DepartReq(departInfo.getRequests(),resp.getDepartId()));
                //向联系方式表中插入数据
                departQQMapper.insert(new DepartQQ(departInfo.getQqNum(),resp.getDepartId()));
                return;
            }
        }
        //权限不足抛出异常
        throw new BusinessException(BusinessExceptionCode.LACK_AUTHORITY);
    }
    /**
     * 编辑部长信息
     */
    public void EditMinisterInfo(HttpServletRequest request, Minister minister) {
        String token = request.getHeader("token");
        //获取响应实体
        UserAdminResp resp = PaeseTokenUtil.getUser(token);
        List<com.linghang.association.domain.Resource> au = resourceMapper.selectByUsername(resp.getUsername());
        LOG.info("" + au);
        for (int i = 0; i < au.size(); i++) {
            //判断是否拥有id为6的权限
            if (au.get(i).getId() == 7) {
                ministerMapper.insert(minister);
                return;
            }
        }
        //权限不足抛出异常
        throw new BusinessException(BusinessExceptionCode.LACK_AUTHORITY);
    }

    /**
     * 管理员打分接口
     * @param id
     */
    public void giveScore(HttpServletRequest request,Integer id,Integer score) {
        String token = request.getHeader("token");
        //获取响应实体
        UserAdminResp resp = PaeseTokenUtil.getUser(token);
        UserSignUp signUp = userSignUpMapper.selectByPrimaryKey(id);
        signUp.setGrades(score);
        List<com.linghang.association.domain.Resource> au = resourceMapper.selectByUsername(resp.getUsername());
        LOG.info("" + au);
        for (int i = 0; i < au.size(); i++) {
            //判断是否拥有id为6的权限
            if (au.get(i).getId() == 1) {
                userSignUpMapper.updateByPrimaryKey(signUp);
                return;
            }
        }
        //权限不足抛出异常
        throw new BusinessException(BusinessExceptionCode.LACK_AUTHORITY);
    }
    /**
     * 查看管理员信息
     */
    public List<ViewAdminResp> viewAdmin(HttpServletRequest request,PageReq req) {
        List<ViewAdminResp> admins = new ArrayList<>();
        String token = request.getHeader("token");
        //获取响应实体
        UserAdminResp resp = PaeseTokenUtil.getUser(token);
        List<com.linghang.association.domain.Resource> au = resourceMapper.selectByUsername(resp.getUsername());
        LOG.info("" + au);
        for (int i = 0; i < au.size(); i++) {
            //判断是否拥有id为4的权限
            if (au.get(i).getId() == 4) {
                PageHelper.startPage(req.getPage(),req.getSize());
                List<UserRole> admin = userRoleMapper.selectByExample(null);
                for(UserRole u:admin){
                    admins.add(new ViewAdminResp(u.getUserName(),roleMapper.selectRoleByUsername(u.getUserName())));
                }
                return admins;
            }
        }
        //权限不足抛出异常
        throw new BusinessException(BusinessExceptionCode.LACK_AUTHORITY);
    }
    /**
     * 发布公告
     * @param notice
     */
    public void releaseNotice(HttpServletRequest request,String notice) {
        String token = request.getHeader("token");
        //获取响应实体
        UserAdminResp resp = PaeseTokenUtil.getUser(token);
        List<com.linghang.association.domain.Resource> au = resourceMapper.selectByUsername(resp.getUsername());
        LOG.info("" + au);
        for (int i = 0; i < au.size(); i++) {
            //判断是否拥有id为5的权限
            if (au.get(i).getId() == 5) {
                //拥有则将其插入在公告栏中
                noticeMapper.insert(new Notice(notice,resp.getDepartId()));
            }
        }
        //权限不足抛出异常
        throw new BusinessException(BusinessExceptionCode.LACK_AUTHORITY);
    }
    /**
     * 发送邮件功能
     * @param qq
     */
    public void sendEmail(String qq){
        //拼接得到邮箱地址
        SimpleMailMessage smm = new SimpleMailMessage();
        smm.setFrom("wustlinghangsudio@163.com");
        //发送地址
        smm.setTo(qq);
        //发送主题
        smm.setSubject("您有一条关于社团报名审核进度的通知");
        //主要内容
        smm.setText("恭喜您成功通过审核，请注意查看社团公告！");
        javaMailSender.send(smm);
    }
}

